using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.AspNetCore.Mvc;
using AuthService.Auth.Dtos;
using Microsoft.AspNetCore.Authorization;
using Swashbuckle.AspNetCore.Annotations;
using AuthService.Services;

namespace AuthService.HttpApi.Controllers
{
    /// <summary>
    /// 认证服务控制器
    /// </summary>
    [ApiController]
    [Route("api/auth")]
    [SwaggerTag("认证服务")]
    public class AuthController : AbpControllerBase
    {
        private readonly IAuthService _authService;

        public AuthController(IAuthService authService)
        {
            _authService = authService;
        }
        /// <summary>
        /// 用户登录
        /// </summary>
        [HttpPost("login")]
        [SwaggerOperation("用户登录")]
        [ProducesResponseType(typeof(LoginResultDto), 200)]
        [ProducesResponseType(401)]
        [ProducesResponseType(403)]
        public virtual async Task<LoginResultDto> LoginAsync([FromBody] LoginRequestDto input)
        {
            return await _authService.LoginAsync(input);
        }

        /// <summary>
        /// 登出
        /// </summary>
        [HttpPost("logout")]
        [SwaggerOperation("登出")]
        [ProducesResponseType(200)]
        public virtual async Task LogoutAsync([FromBody] LogoutRequestDto input)
        {
            await _authService.LogoutAsync(input);
        }

        /// <summary>
        /// 刷新令牌
        /// </summary>
        [HttpPost("refresh")]
        [SwaggerOperation("刷新令牌")]
        [ProducesResponseType(typeof(RefreshTokenResultDto), 200)]
        [ProducesResponseType(401)]
        public virtual async Task<RefreshTokenResultDto> RefreshTokenAsync([FromBody] RefreshTokenRequestDto input)
        {
            return await _authService.RefreshTokenAsync(input);
        }

        /// <summary>
        /// 验证令牌
        /// </summary>
        [HttpPost("validate")]
        [SwaggerOperation("验证令牌")]
        [ProducesResponseType(typeof(TokenValidationResultDto), 200)]
        [ProducesResponseType(401)]
        public virtual async Task<TokenValidationResultDto> ValidateTokenAsync([FromBody] ValidateTokenRequestDto input)
        {
            return await _authService.ValidateTokenAsync(input.Token);
        }

        /// <summary>
        /// 获取令牌信息
        /// </summary>
        [HttpGet("token-info")]
        [SwaggerOperation("获取令牌信息")]
        [ProducesResponseType(typeof(TokenInfoDto), 200)]
        [ProducesResponseType(401)]
        public virtual async Task<TokenInfoDto> GetTokenInfoAsync([FromQuery] string token)
        {
            var validationResult = await _authService.ValidateTokenAsync(token);
            if (!validationResult.IsValid)
            {
                throw new UnauthorizedAccessException("无效的令牌");
            }
            return validationResult.TokenInfo ?? new TokenInfoDto();
        }

        /// <summary>
        /// 获取用户上下文
        /// </summary>
        [HttpGet("user-context")]
        [SwaggerOperation("获取用户上下文")]
        [ProducesResponseType(typeof(UserContextDto), 200)]
        [ProducesResponseType(401)]
        public virtual async Task<UserContextDto> GetUserContextAsync([FromQuery] string token)
        {
            return await _authService.GetUserContextAsync(token);
        }

        /// <summary>
        /// 获取用户信息（需要认证）
        /// </summary>
        [HttpGet("userinfo")]
        [SwaggerOperation("获取用户信息")]
        [ProducesResponseType(typeof(UserContextDto), 200)]
        [ProducesResponseType(401)]
        [Authorize]
        public virtual async Task<UserContextDto> GetUserInfoAsync()
        {
            // 从Authorization Header获取token
            var authorizationHeader = Request.Headers["Authorization"].FirstOrDefault();
            if (string.IsNullOrEmpty(authorizationHeader) || !authorizationHeader.StartsWith("Bearer "))
            {
                throw new UnauthorizedAccessException("缺少有效的Authorization Header");
            }

            var token = authorizationHeader.Substring("Bearer ".Length);
            return await _authService.GetUserContextAsync(token);
        }

        /// <summary>
        /// 检查用户权限
        /// </summary>
        [HttpPost("check-permission")]
        [SwaggerOperation("检查用户权限")]
        [ProducesResponseType(typeof(bool), 200)]
        [ProducesResponseType(401)]
        [Authorize]
        public virtual async Task<bool> CheckPermissionAsync([FromBody] CheckPermissionRequestDto input)
        {
            return await _authService.HasPermissionAsync(input.UserId, input.Permission);
        }

        /// <summary>
        /// 获取用户权限列表
        /// </summary>
        [HttpGet("user-permissions/{userId}")]
        [SwaggerOperation("获取用户权限列表")]
        [ProducesResponseType(typeof(List<string>), 200)]
        [ProducesResponseType(401)]
        [Authorize]
        public virtual async Task<List<string>> GetUserPermissionsAsync(string userId)
        {
            return await _authService.GetUserPermissionsAsync(userId);
        }

        /// <summary>
        /// 获取用户角色列表
        /// </summary>
        [HttpGet("user-roles/{userId}")]
        [SwaggerOperation("获取用户角色列表")]
        [ProducesResponseType(typeof(List<string>), 200)]
        [ProducesResponseType(401)]
        [Authorize]
        public virtual async Task<List<string>> GetUserRolesAsync(string userId)
        {
            return await _authService.GetUserRolesAsync(userId);
        }

        /// <summary>
        /// 密码重置
        /// </summary>
        [HttpPost("reset-password")]
        [SwaggerOperation("密码重置")]
        [ProducesResponseType(200)]
        public virtual async Task ResetPasswordAsync([FromBody] ResetPasswordRequestDto input)
        {
            await _authService.ResetPasswordAsync(input);
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        [HttpPost("change-password")]
        [SwaggerOperation("修改密码")]
        [ProducesResponseType(200)]
        [ProducesResponseType(401)]
        [Authorize]
        public virtual async Task ChangePasswordAsync([FromBody] ChangePasswordRequestDto input)
        {
            await _authService.ChangePasswordAsync(input);
        }
    }

    /// <summary>
    /// 验证令牌请求DTO
    /// </summary>
    public class ValidateTokenRequestDto
    {
        public string Token { get; set; } = string.Empty;
    }

    /// <summary>
    /// 检查权限请求DTO
    /// </summary>
    public class CheckPermissionRequestDto
    {
        public string UserId { get; set; } = string.Empty;
        public string Permission { get; set; } = string.Empty;
    }
    }
}
